package com.achilles.learnasyncqueryhandler;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AchillesL on 2016/6/16.
 */
public class ContactsDataAsyncQueryHandler extends AsyncQueryHandler {

    public interface ContactsDataInterface {
        public void updateDatas(List<ContactsDataModel> contactsDataModels);
    }

    private List<ContactsDataModel> contactsDataModels;
    private ContactsDataInterface mContactsDataInterface;

    public ContactsDataAsyncQueryHandler(ContentResolver cr, ContactsDataInterface
            mContactsDataInterface) {
        super(cr);
        this.mContactsDataInterface = mContactsDataInterface;
        contactsDataModels = new ArrayList<>();
    }

    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
        super.onQueryComplete(token, cookie, cursor);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            do {
                ContactsDataModel contactsDataModel = new ContactsDataModel();
                String contactsName = cursor.getString(0);
                String phoneNumber = cursor.getString(1);

                if (phoneNumber.startsWith("+86")) {
                    phoneNumber = phoneNumber.substring(3);
                }

                contactsDataModel.setContactsName(contactsName);
                contactsDataModel.setPhoneNumber(phoneNumber);

                contactsDataModels.add(contactsDataModel);

            } while (cursor.moveToNext());

            mContactsDataInterface.updateDatas(contactsDataModels);
        }
    }
}
